const Article = require('../models/article')

exports.getArticle = async (req, res) => {
	const { id } = req.params
	try {
		const article = await Article.findById(id)
		console.log(article);
		res.json({
			code: 200,
			msg: '查找成功',
			article,
		})
	} catch (error) {
		res.json({
			code: 403,
			msg: '查找失败',
			error
		})
	}
}

exports.postArticle = async (req, res) => {
	const {title, body} = req.body
	try {
		const article = await Article.create({
			title,
			body
		})
		res.json({
			code: 200,
			msg: '发布成功',
			article,
		})
	} catch (error) {
		res.json({
			code: 403,
			msg: '发布失败',
			error
		})
	}
}

exports.deleteArticle = async (req, res) => {
	const { id } = req.params
	try {
		const article = await Article.findByIdAndUpdate(id, {
			removed: true,
			removedAt: Date.now()
		})
		console.log(article);
		res.json({
			code: 200,
			msg: '删除成功',
			article,
		})
	} catch (error) {
		res.json({
			code: 403,
			msg: '删除失败',
			error
		})
	}
	res.send('article')
}

exports.updateArticle = async (req, res) => {
	const { id } = req.params
	try {
		const article = await Article.findByIdAndUpdate(id, {
			lastModifiedAt: Date.now(),
		})
		console.log(article);
		res.json({
			code: 200,
			msg: '修改成功',
			article,
		})
	} catch (error) {
		res.json({
			code: 403,
			msg: '修改失败',
			error
		})
	}
}